﻿using AutoMapper;
using B.S.Business.Domain;
using B.S.Business.ErrorCode;
using B.S.Business.Infacetrue;
using B.S.Business.Read.API.Applications.Command.SupplierCommand;
using MediatR;
using Microsoft.IdentityModel.Tokens;

namespace B.S.Business.Read.API
{
    public class SupplierQueryCommandHandler : IRequestHandler<SupplierQueryCommand, ApiPaging<SupplierApp>>
    {
        private readonly IBaseRepository<SupplierApp> supplierRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="SupplierRepo"></param>
        /// <param name="mapper"></param>
        public SupplierQueryCommandHandler(IBaseRepository<SupplierApp> supplierRepo, IMapper mapper)
        {
            this.supplierRepo = supplierRepo;
            this.mapper = mapper;
        }

        public Task<ApiPaging<SupplierApp>> Handle(SupplierQueryCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<SupplierApp> result = new ApiPaging<SupplierApp>();
            //查询
            var linq = supplierRepo.GetAll().Where(x => x.IsDeleted == false);
            // 修正条件判断，当输入不为空时进行过滤
            if (!string.IsNullOrEmpty(request.SupplierNumber))
            {
                linq = linq.Where(x => x.SupplierNumber == request.SupplierNumber);
            }
            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                linq = linq.Where(x => x.SupplierName.Contains(request.SupplierName));
            }
            if (!string.IsNullOrEmpty(request.OrderAmount))
            {
                linq = linq.Where(x => x.OrderAmount==request.OrderAmount);
            }
            if (!string.IsNullOrEmpty(request.SupplierPhone))
            {
                linq = linq.Where(x => x.SupplierPhone==request.SupplierPhone);
            }
            //分页
            result.TotalCount = linq.Count();
            result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.Lists = linq.OrderByDescending(x => x.SupplierId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            //返回
            return Task.FromResult(result);
        }
    }
}
